<?php
/**
 * 抽奖管理
 */
namespace Admin\Controller;
use Think\Controller;

class PLotteryController extends CommonController
{
    protected $model;
    protected $return;

    public function __construct(){
        header("Access-Control-Allow-Origin: *");
        $this->return = array('errcode'=>0, 'errmsg'=>'ok');
        $admin = session('rush_admin');
        if (!$admin) {
            $this->ajaxReturn(array('errcode'=>10000,'errmsg'=>'请先登录'));
        }
    }
    //列表
    public function index()
    {
        $data['name']   = I('post.name', '', 'trim');//名称
        $data['status'] = I('post.status', -1, 'intval');//状态0下线1上线
        $data['start']  = I('post.start', '', 'trim');//开始区间
        $data['end']    = I('post.end', '', 'trim'); //结束区间。
        $pageIndex = I('post.page', 1, 'intval');

        $map['is_deleted'] = 0;
        if($data['name'] != ''){
            $map['name'] = array('LIKE', '%'.$data['name'].'%');
        }
        if (in_array($data['status'], array(0,1))) {
            $map['status'] = $data['status'];
        }
        $total = M("PLottery")->where($map)->count();
        $page = pagination($total, 10 ,$pageIndex);
        if($total){
            $res = M("PLottery")->where($map)
            ->limit($page['offset'], $page['limit'])
            ->order('id desc')->select();
        }else{
            $res = array();
        }
        foreach ($res as $k => $v) {
            $res[$k]['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
            $res[$k]['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
            $res[$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
        }
        $this->ajaxReturn(array('errcode'=>0, 'errmsg'=>'ok','data'=>$res,'page'=>$page));
        
    }
 
    //新增
    public function add()
    {
        $data['name'] = I('post.name', '', 'trim');
        $data['start_time'] = I('post.start_time', '', 'trim');
        $data['end_time'] = I('post.end_time', '', 'trim');
        $data['score'] = I('post.score', 0, 'intval');
        if ($data['score'] <= 0) {
            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'抽奖消耗积分不能为0'));
        }
        
        if ($data['name'] == '') {
            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'活动名称不能为空'));
        }
        if($data['start_time'] == ''){
            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'开始时间不能为空'));
        }
        if($data['end_time'] == ''){
            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'结束时间不能为空'));
        }
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        $data['add_time'] = time();
        $data['status'] = 0;
        if($data['start_time'] >= $data['end_time']){
             $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'结束时间必须大于开始时间'));
        }
        $prizes = I('post.prizes');
        if (!is_array($prizes) or empty($prizes)) {
            $this->ajaxReturn(array("errcode"=>10001, 'errmsg'=>'奖品信息为空'));
        }
        if(count($prizes) <3){
            $this->ajaxReturn(array("errcode"=>10002, 'errmsg'=>'需要录入3个以上奖品'));
        }
        $prizesData = array();
        $randCount = 0;
        foreach ($prizes as $k => $v) {
            $name = isset($v['name']) ? trim($v['name']) : '';
            if ($name == '') {
                $this->ajaxReturn(array('errcode'=>10003,'errmsg'=>'奖品名称不能为空'));
            }
            if(mb_strlen($name) > 20){
                $this->ajaxReturn(array('errcode'=>10004,'errmsg'=>'奖品名称过长'));
            }

            $url = isset($v['url']) ? trim($v['url']) : '';
            if ($url == '') {
                $this->ajaxReturn(array('errcode'=>10003,'errmsg'=>'奖品图片不能为空'));
            }
            $sku = isset($v['sku']) ? intval($v['sku']) : 0;
            if ($sku < 0) {
                $this->ajaxReturn(array('errcode'=>10005,'errmsg'=>'奖品库存必须大于等于0'));
            }
            $rand = isset($v['rand']) ? intval($v['rand']) : 0;
            if ($rand > 10000 or $rand < 0){
                $this->ajaxReturn(array('errcode'=>10006,'errmsg'=>'奖品概率错误'));
            }
            $prizesData[] = array('name'=>$name, 'sku'=>$sku, 'surplus'=>$sku, 'rand'=>$rand,'url'=>$url);
            $randCount += $rand;
        }
        if ($randCount != 10000) {
            $this->ajaxReturn(array('errcode'=>10007, 'errmsg'=>'奖品总概率必须等于10000'));
        }
        //开启事务
        $model = M("PLottery");
        $model->startTrans(); 

        
        //插入活动记录
        $res = $model->add($data);
        if($res){
            //插入关联奖品列表
           // $prize = $prize['prize'];
            foreach($prizesData as $k => $v){
                $prizesData[$k]['lottery_id'] = $res;
                $prizesData[$k]['add_time'] = time();
            }
            $insertRes = M('PLotteryPrize')->addAll($prizesData);
            if ($insertRes) {
                //奖品插入成功，提交事务
                $model->commit();
                $this->ajaxReturn($this->return, 'JSON');
            }else{
                //否则，回滚
                $model->rollback();
                $this->ajaxReturn(array('errcode'=>50000,'errmsg'=>'操作失败'), 'JSON');
            }
        }else{
            $model->rollback();
            $this->ajaxReturn(array('errcode'=>50000,'errmsg'=>'操作失败'), 'JSON');
        }
        
    }
    //编辑
    public function edit()
    {
        $id = I('post.id', 0, 'intval');
        $lottery = M("PLottery")->find($id);
        if (!$lottery) {
            $this->ajaxReturn(array('errcode'=>20001, 'errmsg'=>'活动不存在'));
        }

        $lottery['start_time'] = date('Y-m-d H:i:s', $lottery['start_time']);
        $lottery['end_time'] = date('Y-m-d H:i:s', $lottery['end_time']);
        $where['lottery_id'] = $lottery['id'];
        $where['is_deleted'] = 0;
        $prize = M('PLotteryPrize')->where($where)->select();
        $lottery['prize'] = $prize;
        $this->return['data'] = $lottery;
        $this->ajaxReturn($this->return,'JSON');
    }
    //更新数据
    public function update()
    {
        $data['name'] = I('post.name', '', 'trim');
      //  $data['status'] = I('post.status', -1, 'intval');
        $data['start_time'] = I('post.start_time', '', 'trim');
        $data['end_time'] = I('post.end_time', '', 'trim');
        $data['score'] = I('post.score', 0, 'intval');
        $lottery_id = I('post.id', 0, 'intval');
        //var_dump($data);exit;
        if ($data['score'] <= 0) {
            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'抽奖消耗积分不能为0'));
        }
        if ($data['name'] == '') {
            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'活动名称不能为空'));
        }
        if($data['start_time'] == ''){
            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'开始时间不能为空'));
        }
        if($data['end_time'] == ''){
            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'结束时间不能为空'));
        }
        $data['start_time'] = strtotime($data['start_time']);
        $data['end_time'] = strtotime($data['end_time']);
        $data['add_time'] = time();
        if($data['start_time'] >= $data['end_time']){
             $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'结束时间必须大于开始时间'));
        }
        $lottery = M("PLottery")->where(array('id'=>$lottery_id))->find();
        if (!$lottery) {
            $this->ajaxReturn(array('errcode'=>20001, 'errmsg'=>'活动不存在'));
        }
        $prizes = I('post.prizes');
        if (!is_array($prizes) or empty($prizes)) {
            $this->ajaxReturn(array("errcode"=>10001, 'errmsg'=>'奖品信息为空'));
        }

        if(count($prizes) <3){
            $this->ajaxReturn(array("errcode"=>10002, 'errmsg'=>'需要录入3个以上奖品'));
        }

        $prizesData = array();
        $randCount = 0;

        $model = M("PLottery");
        $model->startTrans();

        foreach ($prizes as $k => $v) {
            $name = isset($v['name']) ? trim($v['name']) : '';
            if ($name == '') {
                $this->ajaxReturn(array('errcode'=>10003,'errmsg'=>'奖品名称不能为空'));
            }
            if(mb_strlen($name) > 20){
                $this->ajaxReturn(array('errcode'=>10004,'errmsg'=>'奖品名称过长'));
            }

            $url = isset($v['url']) ? trim($v['url']) : '';
            if ($url == '') {
                $this->ajaxReturn(array('errcode'=>10003,'errmsg'=>'奖品图片不能为空'));
            }

            $sku = isset($v['sku']) ? intval($v['sku']) : 0;
            if ($sku < 0) {
                $this->ajaxReturn(array('errcode'=>10005,'errmsg'=>'奖品库存必须大于等于0'));
            }


            $rand = isset($v['rand']) ? intval($v['rand']) : 0;
            if ($rand > 10000 or $rand < 0){
                $this->ajaxReturn(array('errcode'=>10006,'errmsg'=>'奖品概率错误'));
            }


            $id = isset($v['id']) ? intval($v['id']) : 0;
            $prize = M("PLotteryPrize")->where(array('id'=>$id,'lottery_id'=>$lottery_id))->find();
            if (!$prize) {
                //这里就变成需要新增了
                $id=M("PLotteryPrize")->add(array('lottery_id'=>$lottery_id,'name'=>$name, 'sku'=>$sku, 'rand'=>$rand,'url'=>$url));
            }
            $prizesData[] = array('name'=>$name, 'sku'=>$sku, 'rand'=>$rand, 'id'=>$id,'url'=>$url);
            $randCount += $rand;
        }
        if ($randCount != 10000) {
            $this->ajaxReturn(array('errcode'=>10007, 'errmsg'=>'奖品总概率必须等于10000，现在总值为'.$randCount));
        }

        $res = $model->where(array('id'=>$lottery_id))->save($data);
        if ($res === false) {
            $model->rollback();
            $this->ajaxReturn(array('errcode'=>50000, 'errmsg'=>'更新失败'));
        }
        foreach ($prizesData as $v) {
            $updatePrize = M("PLotteryPrize")->save($v);
            if($updatePrize === false){
                $model->rollback();
                $this->ajaxReturn(array('errcode'=>50000, 'errmsg'=>'更新失败'));
            }
        }
        $model->commit();
        $this->ajaxReturn(array('errcode'=>0, 'errmsg'=>'ok'));
       
    }

    public function copy()
    {
        $id = I('post.id', 0, 'intval');
        $map['is_deleted'] = 0;
        $map['id'] = $id;
        $lottery = M("PLottery")->where($map)->find();
        if (!$lottery) {
            $this->ajaxReturn(array('errcode'=>10001, 'errmsg'=>'要复制的活动不存在'));
        }
        $newLottery = $lottery;
        unset($newLottery['id']);
        $newLottery['add_time'] = time();
        M()->startTrans();
        $res = M("PLottery")->add($newLottery);
        if(!$res){
            M()->rollback();
            $this->ajaxReturn(array('errcode'=>20001,'errmsg'=>'复制失败'));
        }

        $prizeMap['lottery_id'] = $lottery['id'];
        $prizeMap['is_deleted'] = 0;
        $prize = M("PLotteryPrize")->where($prizeMap)->select();
        if(!$prize){
            M()->rollback();
            $this->ajaxReturn(array('errcode'=>20002,'errmsg'=>'奖品信息为空，复制失败'));
        }
        foreach ($prize as $k => $v) {
            unset($prize[$k]['id']);
            $prize[$k]['add_time'] = time();
            $prize[$k]['surplus'] = $v['sku'];
            $prize[$k]['lottery_id'] = $res;
        }
        $insertPrize = M("PLotteryPrize")->addAll($prize);
        if($insertPrize){
            M()->commit();
            $this->ajaxReturn($this->return);
        }else{
            M()->rollback();
            $this->ajaxReturn(array('errcode'=>50000, 'errmsg'=>'复制奖品信息失败'));
        }
    }
   
    public function del()
    {
        $id = I('post.id', 0, 'intval');
        $data['is_deleted'] = 1;
        $res = M("PLottery")->where(array('id'=>$id))->save($data);
        if ($res) {
            $this->ajaxReturn($this->return);
        }else{
            $this->ajaxReturn(array('errcode'=>50000, 'errmsg'=>'删除失败'));
        }
    }

    public function delprize()
    {
        $id = I('post.id', 0, 'intval');
        $data['is_deleted'] = 1;
        $res = M("PLotteryPrize")->where(array('id'=>$id))->save($data);
        if ($res) {
            $this->ajaxReturn($this->return);
        }else{
            $this->ajaxReturn(array('errcode'=>50000, 'errmsg'=>'删除失败'));
        }
    }

    //上下线
    public function changestatus()
    {
        $data['id'] = I('post.id', 0, 'intval');
        $data['status'] = I('post.status');
        if (!in_array($data['status'], array(0,1))) {
            $this->ajaxReturn(array('errcode'=>10001,'errmsg'=>'状态错误'), 'JSON');
        }
        if($data['status'] == 1){
            $upMap['id'] = array('neq', $data['id']);
            M("PLottery")->where($upMap)->save(array('status'=>0));
        }
        $res = M("PLottery")->save($data);
        if ($res!== false) {
            $this->ajaxReturn($this->return, 'JSON');
        }else{
            $this->ajaxReturn(array('errcode'=>50000,'errmsg'=>'操作失败'), 'JSON');
        }
        // //如果上线，确认同一时间只允许一个活动上线
        // if (!$lottery = $this->model->canChangeStatus($data['id'], $data['status'])) {
        //     $this->ajaxReturn($this->model->getErrMsg(), 'JSON');
        // }
        // $data['update_time'] = time();
        // if ($data['status'] == 1) {
        //     $map['type'] = $lottery['type'];
        //     $this->model->where($map)->save(array('status'=>0));
        // }
        // $res = $this->model->save($data);
        // if($res !== false){
        //     $this->model->clearCache($data['id']);
        //     $this->model->operatelog($this->userId, $this->userName, '签到活动', 3, $data['id']);
        //     $this->ajaxReturn($this->return, 'JSON');
        // }else{
        //     $this->ajaxReturn(array('errcode'=>50000,'errmsg'=>'更新失败'), 'JSON');
        // }

    }
    
 
    /**
     * 查看日志
     * @return [type] [description]
     */
    public function record()
    {
        $data['phone'] = I('post.phone', '', 'trim');
        $data['account'] = I('post.account', '', 'trim');
        $data['keyword'] = I('keyword', '', 'trim');
        $data['name'] = I('post.name', '', 'trim');
        $data['start'] = I('post.start', '', 'trim');
        $data['end'] = I('post.end', '', 'trim');

        $model = M('PScoreRecord');
        $model->alias('r')->join('__P_USER__ u ON u.id = r.user_id', 'LEFT')
              ->join('__P_LOTTERY_PRIZE__ p ON r.prize_id = p.id', 'LEFT');
        //组装查询条件
        $where['r.is_deleted'] = 0;
        $where['r.type'] = 4;

        if(isset($data['keyword']) and $data['keyword'] != ''){
            $or['u.name'] = array('LIKE', '%'.$data['keyword'].'%');
            $or['u.phone'] = array('LIKE', '%'.$data['keyword'].'%');
            $or['u.account'] = array('LIKE', '%'.$data['keyword'].'%');
            $or['_logic'] = 'or';
            $where['_complex'] = $or;
        }
        //活动名称
        if (isset($data['name']) and $data['name'] != '') {
            $where['p.name'] = array('LIKE', '%'.$data['name'].'%');
        }
        
        
        //活动创建时间开始区间
        if (isset($data['start']) and $data['start']) {
            $where['r.add_time'][] = array('egt', strtotime($data['start']));
        }
        //活动创建时间结束区间
        if (isset($data['end']) and $data['end']) {
            $where['r.add_time'][] = array('elt', strtotime($data['end'].' 23:59:59'));
        }
        
        $total = $model->where($where)->count();
        $pageIndex = I('post.page') ?: 1;
        $pageSize = I('post.page_size') ?: 20;
        $page = pagination($total, $pageSize ,$pageIndex);
        if ($total) {
            if($down){
                $list = $model->alias('r')
                        ->field('r.*,u.name as username,u.account,u.phone,u.address,p.name')
                        ->join('__P_USER__ u ON u.id = r.user_id', 'LEFT')
                        ->join('__P_LOTTERY_PRIZE__ p ON r.prize_id = p.id', 'LEFT')
                        ->where($where)->order('r.id desc')->select();
            }else{
                $list = $model->alias('r')
                        ->field('r.*,u.name as username,u.account,u.phone,u.address,p.name')
                        ->join('__P_USER__ u ON u.id = r.user_id', 'LEFT')
                        ->join('__P_LOTTERY_PRIZE__ p ON r.prize_id = p.id', 'LEFT')
                        ->where($where)->order('r.id desc')
                        ->limit($page['offset'], $page['limit'])->select();
              }
            foreach ($list as $k => $v) {
                $list[$k]['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
                $list[$k]['score'] = abs($v['score']);
            }
            $res = array('data'=>$list, 'page'=>$page);
        }else{
            $res = array('data'=>array(), 'page'=>$page);
        }
        return $this->ajaxReturn(array_merge($this->return, $res));
       
    }

    
    //导出
    public function download()
    {
        $data['start'] = I('post.start', '', 'trim');
        $data['end']   = I('post.end', '', 'trim');
        $data['rec_id'] = I('post.rec_id', '', 'trim');
        $data['lottery_id'] = I('post.lottery_id', '', 'trim');
        $data['user_id'] = I('post.user_id', '', 'trim');
        $data['user_name'] = I('post.user_name', '', 'trim');
        $data['type'] = I('post.type', 0, 'intval');
        $data['name'] = I('post.name', '', 'trim');
        $data['page'] = I('post.page', 1, 'intval');
        $data['page_size'] = I('page_size', 10, 'intval');

        $res = $this->model->getLogList($data, true);
        $sheetindex=array(
            'A'=>array('index'=>'A1','name'=>'序号','size'=>'20'),
            'B'=>array('index'=>'B1','name'=>'流水号','size'=>'20'),
            'C'=>array('index'=>'C1','name'=>'活动编号','size'=>'20'),
            'D'=>array('index'=>'D1','name'=>'名称','size'=>'20'),
            'E'=>array('index'=>'E1','name'=>'参与者ID','size'=>'20'),
            'F'=>array('index'=>'F1','name'=>'参与者','size'=>'20'),
            'G'=>array('index'=>'G1','name'=>'获奖情况','size'=>'20'),
            'H'=>array('index'=>'H1','name'=>'获奖金额','size'=>'20'),
            'I'=>array('index'=>'I1','name'=>'参与时间','size'=>'20'),
        );
        $title = '签到日志';
        $type = 15;
        phpExcel($sheetindex,$res['data'],$title,$type);
        exit;
    }
   

}